/*********************************************************
          File Name:lock.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 13 Aug 2015 09:04:56 PM CST
**********************************************************/

#include "lock.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>

static pthread_mutex_t *accept_lock = NULL;

void acc_init(void)
{
        int fd = 0;
        pthread_mutexattr_t attr;

        fd = open("/dev/zero", O_RDWR);

        accept_lock = (pthread_mutex_t *)mmap(0, sizeof(pthread_mutex_t), 
                        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        close(fd);

        pthread_mutexattr_init(&attr);
        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        pthread_mutex_init(accept_lock, &attr);
}

void acc_lock(void)
{
        pthread_mutex_lock(accept_lock);
}

void acc_release(void)
{
        pthread_mutex_unlock(accept_lock);
}

void acc_vanish(void)
{
        munmap(accept_lock, sizeof(pthread_mutex_t));
}
